import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/edit_text_field.dart';
import 'package:qunaimedical/components/input_option.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/patient.dart';
import 'package:qunaimedical/models/patient_record.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

/// 患者病例添加
class PatientRecordAddPage extends StatefulWidget {
  final Patient patient;

  /// 病例id，用于获取病例详情
  final String id;

  const PatientRecordAddPage(this.patient, {Key key, this.id})
      : super(key: key);

  @override
  _PatientRecordAddPageState createState() => _PatientRecordAddPageState();
}

class _PatientRecordAddPageState extends State<PatientRecordAddPage> {
  TextEditingController _contentController = TextEditingController();
  TextEditingController _historyController = TextEditingController();
  TextEditingController _resultController = TextEditingController();
  TextEditingController _suggestController = TextEditingController();

  String _time;

  @override
  void initState() {
    super.initState();
    if (widget.id != null) {
      _fetchData();
    }
  }

  /// 获取病例详情
  void _fetchData() async {
    var data =
        await XHttp.get(sprintf(Urls.PATIENT_RECORD_DETAIL, [widget.id]));
    if (data != null && mounted) {
      var response = MapResponse.fromJson(data);
      PatientRecord item = PatientRecord.fromJson(response.data);
      setState(() {
        _time = item.checkTime;
        _contentController.text = item.content;
        _historyController.text = item.history;
        _suggestController.text = item.suggestion;
        _resultController.text = item.diagnosis;
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    _contentController.dispose();
    _historyController.dispose();
    _resultController.dispose();
    _suggestController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String title;
    if (widget.id != null) {
      title = '病例详情';
    } else {
      title = '添加病例';
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: ListView(
              padding: EdgeInsets.symmetric(vertical: 10),
              children: [
                PrimaryLabel('基本信息'),
                TextOption(
                  label: '医师姓名：',
                  secondText: SPUtils.getUser().fullname,
                  hideArrow: true,
                ),
                TextOption(
                  label: '患者姓名：',
                  secondText: widget.patient.fullname,
                  hideArrow: true,
                ),
                TextOption(
                  label: '就诊时间：',
                  onTap: () => _selectTime(context),
                  secondText: _time ?? '请选择时间',
                  secondTextColor: _time == null ? Colors.grey : Colors.black,
                ),
                CustomDivider(),
                PrimaryLabel('主诉'),
                EditTextField(
                  maxLines: 5,
                  maxLength: 400,
                  hintText: '请输入您要主诉的内容',
                  controller: _contentController,
                ),
                CustomDivider(),
                PrimaryLabel('病史'),
                EditTextField(
                  maxLines: 5,
                  maxLength: 400,
                  hintText: '请输入病史内容',
                  controller: _historyController,
                ),
                CustomDivider(),
                PrimaryLabel('初步诊断'),
                EditTextField(
                  maxLines: 5,
                  maxLength: 400,
                  hintText: '请输入初步诊断',
                  controller: _resultController,
                ),
                CustomDivider(),
                PrimaryLabel('处理意见'),
                EditTextField(
                  maxLines: 5,
                  maxLength: 400,
                  hintText: '请输入处理意见',
                  controller: _suggestController,
                ),
              ],
            ),
          ),
          PrimaryButton('提交', onPressed: _create),
        ],
      ),
    );
  }

  /// 选择预约时间
  void _selectTime(BuildContext context) async {
    CommonUtils.hideKeyboard(context);
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime.now().subtract(Duration(days: 365 * 10)),
        maxTime: DateTime.now(), onConfirm: (date) {
      setState(() {
        _time = date.toString().substring(0, 16);
      });
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  void _create() async {
    CommonUtils.hideKeyboard(context);
    String content = _contentController.text.trim();
    String history = _historyController.text.trim();
    String result = _resultController.text.trim();
    String suggest = _suggestController.text.trim();
    if (_time == null) {
      ToastUtil.show('请输入就诊时间', context);
      return;
    }
    if (content.isEmpty) {
      ToastUtil.show('请输入主诉内容', context);
      return;
    }
    if (history.isEmpty) {
      ToastUtil.show('请输入病史内容', context);
      return;
    }
    if (result.isEmpty) {
      ToastUtil.show('请输入初步诊断内容', context);
      return;
    }
    if (suggest.isEmpty) {
      ToastUtil.show('请输入处理意见', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var params = {
      "doctorAccountId": SPUtils.getUser().id, //医生account id
      "patientAccountId": widget.patient.patiAccountId, //患者账号id
      "content": content,
      "history": history,
      "diagnosis": result,
      "suggestion": suggest,
      "checkTime": '$_time:00', //诊断时间
    };
    if (widget.id != null) {
      params['id'] = widget.id;
    }
    var data = await XHttp.postJson(
        widget.id == null
            ? Urls.PATIENT_RECORD_ADD
            : Urls.PATIENT_RECORD_UPDATE,
        params);
    Navigator.pop(context);
    if (data != null) {
      var response = MapResponse.fromJson(data);
      if (response.code == 1) {
        ToastUtil.show('操作成功', context);
        Navigator.pop(context, true);
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
